--[[
Copyright:www.vxinyou.com
Author:Hongru
CreateTime:2015-03-19
Description:统计函数调用次数，会影响性能，仅仅做分析使用
--]]

--[[
统计：
local a = MOD_PROFILER.profilerFactory()
a()
关闭:
MOD_PROFILER.turnOffHooks()
]]

module ( ..., package.seeall ) 

--闭包工厂
function profilerFactory()

	local Counters = {}
	local Names = {}

	function hook ()
		local f = debug.getinfo ( 2, "f" ).func -- stack level 2
		if not Counters[ f ] then
			Counters[ f ] = 1
			Names[f] = debug.getinfo ( 2, "Sn" )
		else
			Counters[ f ] = Counters[ f ] + 1
		end
	end

	function setHook ()
		debug.sethook (  hook , "c"  )
	end

	function getname ( func )
		local n = Names[ func ]
		if n.what == "C" then
			return n.name
		end
		local lc = string.format ( "[%s]:%s", n.short_src, n.linedefined )
		if n.namewhat ~= "" then
			return string.format ( "%s (%s)", lc, n.name )
		else
			return n.namewhat .. " " .. lc
		end
	end

	function showResult ()
		for func, count in pairs ( Counters ) do
			print ( getname (func), "次数" .. count)
		end
	end
	
	setHook ()
	
	return showResult --闭包
end

--turn off hooks
function turnOffHooks ()
	debug.sethook ()
end





